package com.example.tests;

import java.util.concurrent.TimeUnit;

import com.example.pages.CreatedMoviePage;
import com.example.pages.LoginPage;
import com.example.pages.MovieCreationPage;
import com.example.pages.MovieListPage;
import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.*;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.esteru.selenium.factory.WebDriverFactory;
import org.openqa.selenium.remote.DesiredCapabilities;

public class AddMovie {
    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();
    private LoginPage loginPage;
    private MovieListPage newMoviePage;
    private MovieCreationPage newMovieCreatePage;
    private CreatedMoviePage newCreatedMoviePage;
    private WebDriverWait wait;

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://127.0.0.1/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        wait = new WebDriverWait(driver, 10);
    }

    @Test
    public void testAddMovie() throws Exception {
        goToMainPage();
        loginAS("admin","admin");
        AddNewMovie("Test", "1987");
        //redirect to movie page after creation
        assertTrue("This is not movie page", newCreatedMoviePage.isOnMoviePage());
        LogOut();
    }

    @After
    public void tearDown() throws Exception {
        //driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private void LogOut() {
        newMoviePage.menuLogoutLink.click();
        wait.until(alertIsPresent()).accept();
    }

    private void loginAS(String username, String password) {
        loginPage.userNameField.clear();
        loginPage.userNameField.sendKeys(username);
        loginPage.passwordField.clear();
        loginPage.passwordField.sendKeys(password);
        loginPage.loginButton.click();

    }

    private void goToMainPage() {
        // open main page
        driver.get(baseUrl + "/php4dvd/");
        loginPage = PageFactory.initElements(driver, LoginPage.class);
        newMoviePage = PageFactory.initElements(driver, MovieListPage.class);
        newMovieCreatePage = PageFactory.initElements(driver, MovieCreationPage.class);
        newCreatedMoviePage = PageFactory.initElements(driver, CreatedMoviePage.class);

    }

    private void AddNewMovie(String filmname, String year){
        newMoviePage.addMovieButton.click();
        newMovieCreatePage.titleEditField.sendKeys(filmname);
        newMovieCreatePage.yearEditField.sendKeys(year);
        newMovieCreatePage.saveButton.click();
    }
}
